package com.alibaba.easyexcel.test.demo.read;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;

/**
 * 模板的读取类
 *
 * @author Jiaju Zhuang
 */
public class IndexOrNameDataListener extends AnalysisEventListener<IndexOrNameData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(IndexOrNameDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<IndexOrNameData> list = new ArrayList<IndexOrNameData>();

    @Override
    public void invoke(IndexOrNameData data, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        Map<Integer, Cell> cellMap = readRowHolder.getCellMap();
        for (Map.Entry<Integer, Cell> entry : cellMap.entrySet()) {
            Integer column = entry.getKey();
            Cell cell = entry.getValue();

        }
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
//        if (list.size() >= BATCH_COUNT) {
//            saveData();
//            list.clear();
//        }
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        String sheetName = context.readSheetHolder().getSheetName();
        switch (extra.getType()) {
            case MERGE: // 额外信息是合并单元格
                Integer firstColumnIndex = extra.getFirstColumnIndex();
                Integer lastColumnIndex = extra.getLastColumnIndex();
                Integer firstRowIndex = extra.getFirstRowIndex();
                Integer lastRowIndex = extra.getLastRowIndex();
                System.out.println();
                break;
            case COMMENT:
            case HYPERLINK:
            default:
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        LOGGER.info("存储数据库成功！");
    }


}
